﻿using Microsoft.Win32;
using System;

using System.Windows;
using System.Windows.Controls;

using System.Windows.Media;
using System.Windows.Shapes;

using System.Net;
using System.Net.Sockets;
using System.IO;
using Autodesk.Revit.UI;
using System.Windows.Media.Imaging;
using System.Windows.Input;

namespace component
{
    /// <summary>
    /// NavagationPage2.xaml 的交互逻辑
    /// </summary>
    public partial class NavagationPage2 : UserControl
    {
        public static int serverPort1 = 8888;//服务端端口
        
        public NavagationPage2()
        {

            InitializeComponent();
        }
        private int addButton = 0;
        private Button download_button = new Button();
        private Button set_button = new Button();
        private Button del_button = new Button();
        private Button button = new Button();
        //上传文件
        public static string serverIp = "127.0.0.1";//设置服务端IP
        public static int serverPort = 8899;//服务端端口
        public static Socket socketClient;//定义socket
        private void Upload_Click(object sender, RoutedEventArgs e)
        {
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket的对象
            IPAddress ip = IPAddress.Parse(serverIp);//获取服务器IP地址
            IPEndPoint point = new IPEndPoint(ip, serverPort);//获取端口
            //try
            //{
                Console.WriteLine("连接服务器中.....");
                socketClient.Connect(point);//链接服务器IP与端口
                Console.WriteLine("与服务器链接成功！");
                Upload();
                Console.WriteLine("上传成功!");
               
            
            //catch (Exception ex)
            //{
                //TaskDialog.Show("upload_click", ex.Message);
                //Console.WriteLine("上传失败！");
                //return;
            //}
            
           
            

            putComponent.Children.Add(button);
            button.Margin = new Thickness(5, 5, 0, 0);
            button.Width = 70;
            button.Height = 100;
            button.Click += key_click;
            //Grid grid = new Grid();
            //button.Content = grid;
            //Image image = new Image();
            //Uri resourceUri = new Uri(@"F:\img\4.png", UriKind.Relative);
            //image.Source = new BitmapImage(resourceUri);
            ////grid.Children.Add(image);
            //button.Content = image;
            //image.Stretch = Stretch.Fill;
            //if (button.IsPressed)
            //    key_click(sender, e);
            //else download_button.Visibility = Visibility.Collapsed;
            //按钮背景
            ImageBrush brush = new ImageBrush();
            brush.ImageSource = new BitmapImage(new Uri(@"F:\img\4.png", UriKind.Relative));
            button.Background = brush;
            //面板中加入按钮
            putKey.Children.Add(set_button);
            putKey.Children.Add(download_button);
            putKey.Children.Add(del_button);

            set_button.Content = "布置";
            set_button.Width = 50;
            set_button.Height = 20;
            set_button.Margin = new Thickness(5, 5, 5, 5);
            set_button.Visibility = Visibility.Collapsed;


            download_button.Content = "下载";
            download_button.Width = 50;
            download_button.Height = 20;

            download_button.Visibility = Visibility.Collapsed;

            del_button.Content = "删除";
            del_button.Width = 50;
            del_button.Height = 20;
            del_button.Margin = new Thickness(5, 5, 5, 5);
            del_button.Visibility = Visibility.Collapsed;
            del_button.VerticalAlignment = VerticalAlignment.Top;
            del_button.Click += Del_button_Click;
            download_button.Click += Download_button_Click1;
            MessageBox.Show("发送完成", "进度");
        }

        private static void Upload()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "选择要传的文件";
            ofd.InitialDirectory = @"E:\存放";//获取或设置文件对话框显示的初始目录。
            ofd.ShowDialog();//打开
            //得到选择文件的路径
            string file_path = ofd.FileName;//获取文件的完整路径
            //FileStream表示在磁盘或网络路径上指向文件的流。
            using (FileStream fsRead = new FileStream(file_path, FileMode.OpenOrCreate, FileAccess.Read))
            {
                //第一步：发送一个文件，表示文件名和长度，让客户端知道后续要接收几个包来重新组织成一个文件
                string filename = System.IO.Path.GetFileName(file_path);
                byte[] filename_Byte = System.Text.Encoding.UTF8.GetBytes(filename);//文件名的数组
                byte[] filenameLength = new byte[1];//文件名长度的数组
                filenameLength[0] = (byte)filename_Byte.Length;
                socketClient.Send(filenameLength);//发送文件名长度
                socketClient.Send(filename_Byte);//发送文件名
                long fileLength = fsRead.Length;//文件长度
                //发送文件长度
                string fileLength_string = fileLength.ToString();
                Console.WriteLine("文件长度是：" + fileLength_string);
                byte[] fileLength_byte = System.Text.Encoding.UTF8.GetBytes(fileLength_string);
                byte[] fileLength_byteLengthB = new byte[1];
                fileLength_byteLengthB[0] = (byte)fileLength_byte.Length;
                socketClient.Send(fileLength_byteLengthB);//发送关于文件长度数组的长度
                socketClient.Send(fileLength_byte);//发送文件长度数组
                //第二步：每次发送一个1MB的包，如果文件较大，则会拆分为多个包
                byte[] Filebuffer = new byte[1024 * 1024];//定义1MB的缓存空间
                int readLength = 0;  //定义读取的长度
                long sentFileLength = 0;//定义发送的长度
                while ((readLength = fsRead.Read(Filebuffer, 0, Filebuffer.Length)) > 0 && sentFileLength < fileLength)
                {
                    sentFileLength += readLength;
                    socketClient.Send(Filebuffer, 0, readLength, SocketFlags.None);
                    Console.WriteLine("{0}: 已发送数据：{1}/{2}", socketClient.RemoteEndPoint, sentFileLength, fileLength);
                }
                Commons.ExactFamily(Commons.commandData, file_path);
                fsRead.Close();
                //OpenFileDialog ofd = new OpenFileDialog();
                //ofd.Title = "选择要传的文件";
                //ofd.InitialDirectory = @"E:\存放";//获取或设置文件对话框显示的初始目录。
                //ofd.ShowDialog();//打开
                //                 //得到选择文件的路径
                //string file_path = ofd.FileName;//获取文件的完整路径
                //MessageBox.Show(file_path);

                //    //FileStream表示在磁盘或网络路径上指向文件的流。
                //    using (FileStream fsRead = new FileStream(file_path, FileMode.OpenOrCreate, FileAccess.Read))
                //{
                //    //第一步：发送一个文件，表示文件名和长度，让客户端知道后续要接收几个包来重新组织成一个文件
                //    string filename = System.IO.Path.GetFileName(file_path);
                //    byte[] filename_Byte = System.Text.Encoding.UTF8.GetBytes(filename);//文件名的数组
                //    byte[] filenameLength = new byte[1];//文件名长度的数组
                //    filenameLength[0] = (byte)filename_Byte.Length;
                //    socketClient.Send(filenameLength);//发送文件名长度
                //    socketClient.Send(filename_Byte);//发送文件名
                //    long fileLength = fsRead.Length;//文件长度
                //                                    //发送文件长度
                //    string fileLength_string = fileLength.ToString();
                //    Console.WriteLine("文件长度是：" + fileLength_string);
                //    byte[] fileLength_byte = System.Text.Encoding.UTF8.GetBytes(fileLength_string);
                //    byte[] fileLength_byteLengthB = new byte[1];
                //    fileLength_byteLengthB[0] = (byte)fileLength_byte.Length;
                //    socketClient.Send(fileLength_byteLengthB);//发送关于文件长度数组的长度
                //    socketClient.Send(fileLength_byte);//发送文件长度数组
                //                                       //发送MD5
                //    byte[] MD5_byte = System.Text.Encoding.UTF8.GetBytes(Commons.GetMD5HashFromFile(file_path));
                //    byte[] MD5_byteLengthB = new byte[1];
                //    MD5_byteLengthB[0] = (byte)MD5_byte.Length;
                //    socketClient.Send(MD5_byteLengthB);//发送关于文件长度数组的长度
                //    socketClient.Send(MD5_byte);//发送文件长度数组
                //                                //第二步：每次发送一个1MB的包，如果文件较大，则会拆分为多个包
                //    byte[] Filebuffer = new byte[1024 * 1024];//定义1MB的缓存空间
                //    int readLength = 0;  //定义读取的长度
                //    long sentFileLength = 0;//定义发送的长度
                //    while ((readLength = fsRead.Read(Filebuffer, 0, Filebuffer.Length)) > 0 && sentFileLength < fileLength)
                //    {
                //        sentFileLength += readLength;
                //        socketClient.Send(Filebuffer, 0, readLength, SocketFlags.None);
                //        Console.WriteLine("{0}: 已发送数据：{1}/{2}", socketClient.RemoteEndPoint, sentFileLength, fileLength);
                //    }
                //    fsRead.Close();
                //}
                Console.ReadLine();
                FamilyToJson familyToJson = new FamilyToJson();
                string family_json = familyToJson.ExactFamily(Commons.commandData, file_path);
                Commons.Insert(family_json);
            }
        }

        private void Del_button_Click(object sender, RoutedEventArgs e)
        {
            putComponent.Children.Remove(button);
        }
       
        private void key_click(object sender, RoutedEventArgs e)
        {
            if (addButton == 0)
            {
                del_button.Visibility = Visibility.Visible;
                set_button.Visibility = Visibility.Visible;
                download_button.Visibility = Visibility.Visible;
                addButton += 1;
            }
            else
            {
                del_button.Visibility = Visibility.Collapsed;
                set_button.Visibility = Visibility.Collapsed;
                download_button.Visibility = Visibility.Collapsed;
                addButton -= 1;
            }
        }

           

          private void Download_button_Click1(object sender, RoutedEventArgs e)
            {
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket的对象
                IPAddress ip = IPAddress.Parse(serverIp);//获取服务器IP地址
                IPEndPoint point = new IPEndPoint(ip, serverPort1);//获取端口
                try
                {
                    socketClient.Connect(point);//链接服务器IP与端口
                    Console.WriteLine("连接服务器中.....");

                }
                catch (Exception)
                {
                    Console.WriteLine("与服务器链接失败！");
                    return;
                }
            Console.WriteLine("与服务器链接成功！");
            String filename = "窗洞.rfa";
            byte[] filename_Byte = System.Text.Encoding.UTF8.GetBytes(filename);//文件名的数组
            byte[] filenameLength = new byte[1];//文件名长度的数组
            filenameLength[0] = (byte)filename_Byte.Length;
            socketClient.Send(filenameLength);//发送文件名长度
            socketClient.Send(filename_Byte);//发送文件名
            Console.Write("发送请求完毕");
            byte[] fileLength = new byte[socketClient.ReceiveBufferSize];//接受文件长度的数组
            socketClient.Receive(fileLength);//接受文件长度
            long filelong = BytesToLong(fileLength);
            System.Windows.Forms. FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            Console.WriteLine("执行完毕");
            dialog.ShowDialog();
            string file_path = dialog.SelectedPath;
            //得到选择文件的路径
            //string spath = @"E:\存放";//制定存储路径
            string savePath = System.IO.Path.Combine(file_path, filename);//获取存储路径及文件名
            FileStream fileStream1 = new FileStream(savePath, FileMode.Create, FileAccess.Write);
            int rec = 0;//每次转换的长度
            long recFileLength = 0;//接受的文件长度
            byte[] buffer = new byte[1024];//接受文件的数组
            while (recFileLength < filelong)
            {
                rec = socketClient.Receive(buffer);
                fileStream1.Write(buffer, 0, rec);
                fileStream1.Flush();
                recFileLength++;
            }
            fileStream1.Close();
        }
            //将字符数组转换成Long型的方法
           
        static long BytesToLong(byte[] bytes)
        {
            return BitConverter.ToInt64(bytes, 0);
        }
    }
}
